const state = {
  favorites: [],
  searchResults: [],
  searchHistory: []
}

const mutations = {
  SET_SEARCH_RESULTS(state, results) {
    state.searchResults = results
  },
  ADD_TO_FAVORITES(state, drug) {
    if (!state.favorites.find(f => f.id === drug.id)) {
      state.favorites.push(drug)
      uni.setStorageSync('drugFavorites', state.favorites)
    }
  },
  REMOVE_FROM_FAVORITES(state, drugId) {
    state.favorites = state.favorites.filter(f => f.id !== drugId)
    uni.setStorageSync('drugFavorites', state.favorites)
  },
  LOAD_FAVORITES(state) {
    const favorites = uni.getStorageSync('drugFavorites') || []
    state.favorites = favorites
  },
  ADD_SEARCH_HISTORY(state, keyword) {
    if (!state.searchHistory.includes(keyword)) {
      state.searchHistory.unshift(keyword)
      if (state.searchHistory.length > 10) {
        state.searchHistory = state.searchHistory.slice(0, 10)
      }
      uni.setStorageSync('drugSearchHistory', state.searchHistory)
    }
  }
}

const actions = {
  // 搜索药品
  async searchDrug({ commit }, keyword) {
    try {
      // 模拟API调用
      const mockResults = [
        {
          id: '1',
          name: '阿莫西林胶囊',
          category: '抗生素',
          manufacturer: '华北制药',
          price: '12.5',
          description: '用于治疗敏感菌所致的各种感染'
        },
        {
          id: '2',
          name: '布洛芬缓释胶囊',
          category: '解热镇痛',
          manufacturer: '扬子江药业',
          price: '18.0',
          description: '用于缓解轻至中度疼痛'
        }
      ]
      
      commit('SET_SEARCH_RESULTS', mockResults)
      commit('ADD_SEARCH_HISTORY', keyword)
      return mockResults
    } catch (error) {
      console.error('搜索药品失败:', error)
      return []
    }
  },

  // 添加到收藏
  addToFavorites({ commit }, drug) {
    commit('ADD_TO_FAVORITES', drug)
  },

  // 从收藏中移除
  removeFromFavorites({ commit }, drugId) {
    commit('REMOVE_FROM_FAVORITES', drugId)
  },

  // OCR识别
  async ocrRecognize({ commit }, imagePath) {
    try {
      // 模拟OCR API调用
      const mockResult = {
        success: true,
        text: '阿莫西林胶囊 0.25g*24粒',
        confidence: 0.95,
        drugs: [
          {
            name: '阿莫西林胶囊',
            specification: '0.25g*24粒',
            confidence: 0.95
          }
        ]
      }
      
      return mockResult
    } catch (error) {
      console.error('OCR识别失败:', error)
      return { success: false, error: error.message }
    }
  },

  // 加载收藏
  loadFavorites({ commit }) {
    commit('LOAD_FAVORITES')
  }
}

const getters = {
  favorites: state => state.favorites,
  searchResults: state => state.searchResults,
  searchHistory: state => state.searchHistory
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}